package com.ruoyi.duty.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.vo.IsPlaceInfo;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.duty.domain.DutyTc;
import com.ruoyi.duty.domain.bo.DutyTcBo;
import com.ruoyi.common.core.domain.vo.DutyTcVo;
import com.ruoyi.duty.mapper.DutyTcMapper;
import com.ruoyi.duty.service.IDutyTcService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 房屋踏查Service业务层处理
 *
 * @author xiaohao
 * @date 2023-01-19
 */
@RequiredArgsConstructor
@Service
public class DutyTcServiceImpl implements IDutyTcService {

    private final DutyTcMapper baseMapper;

    /**
     * 查询房屋踏查
     */
    @Override
    public DutyTcVo queryById(Long tcId) {
        return baseMapper.selectVoById(tcId);
    }

    /**
     * 查询房屋踏查列表
     */
    @Override
    public TableDataInfo<DutyTcVo> queryPageList(DutyTcBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DutyTc> lqw = buildQueryWrapper(bo);
        Page<DutyTcVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询房屋踏查列表
     */
    @Override
    public List<DutyTcVo> queryList(DutyTcBo bo) {
        LambdaQueryWrapper<DutyTc> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DutyTc> buildQueryWrapper(DutyTcBo bo) {
        LambdaQueryWrapper<DutyTc> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getMemberId() != null, DutyTc::getMemberId, bo.getMemberId());
        lqw.eq(bo.getPlaceId() != null, DutyTc::getPlaceId, bo.getPlaceId());
        lqw.eq(StrUtil.isNotBlank(bo.getTcResult()), DutyTc::getTcResult, bo.getTcResult());
        return lqw;
    }

    /**
     * 新增房屋踏查
     */
    @Override
    public Boolean insertByBo(DutyTcBo bo) {
        DutyTc add = BeanUtil.toBean(bo, DutyTc.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setTcId(add.getTcId());
        }
        return flag;
    }

    /**
     * 修改房屋踏查
     */
    @Override
    public Boolean updateByBo(DutyTcBo bo) {
        DutyTc update = BeanUtil.toBean(bo, DutyTc.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DutyTc entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除房屋踏查
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void renderTcInfo(List<? extends IsPlaceInfo> list) {
        List<Long> placeIds = list.stream().map(IsPlaceInfo::getPlaceId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(placeIds)) {
            List<DutyTcVo> dutyTcVoList = baseMapper.selectVoList(Wrappers.<DutyTc>lambdaQuery().in(DutyTc::getPlaceId, placeIds));
            Map<Long, List<DutyTcVo>> tcVoMap = Maps.newHashMap();
            dutyTcVoList.forEach(tc -> {
                if (!tcVoMap.containsKey(tc.getPlaceId())) {
                    tcVoMap.put(tc.getPlaceId(), Lists.newArrayList());
                }
                tcVoMap.get(tc.getPlaceId()).add(tc);
            });
            list.forEach(place -> {
                if (tcVoMap.containsKey(place.getPlaceId())) {
                    place.setTcInfo(getRecentTcVo(tcVoMap.get(place.getPlaceId())));
                    place.setTcInfoList(tcVoMap.get(place.getPlaceId()));
                }
            });
        }
    }

    private DutyTcVo getRecentTcVo(List<DutyTcVo> dutyTcVoList) {
        if (CollUtil.isEmpty(dutyTcVoList)) return null;
        if (dutyTcVoList.size() == 1) return dutyTcVoList.get(0);
        return dutyTcVoList.stream().max(Comparator.comparing(DutyTcVo::getTcTime)).get();
    }


}
